//
//  TradingRecordVC.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/8.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import MJRefresh

class TradingRecordVC: BaseVC, UITableViewDelegate, UITableViewDataSource, CTAPIManagerCallBackDelegate, CTAPIManagerParamSource, UISearchBarDelegate
{
    
    // MARK: - Life Cycle
    override func loadView() {
        
        view = tableView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "TradingRecordCell", bundle: nil), forCellReuseIdentifier: "CellID")
        tableView.register(TradingRecordHeaderView.classForCoder(), forHeaderFooterViewReuseIdentifier: "HeaderID")
        tableView.keyboardDismissMode = .onDrag
        
        searchBar.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocalStr("收付记录")
        // Do any additional setup after loading the view.
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_日历筛选").renderOriginal(), style: .plain, target: self, action: #selector(点击时间筛选))
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshHeader))
        tableView.mj_header.beginRefreshing()
    }
    
    // MARK: - Table View Data Source
    func numberOfSections(in tableView: UITableView) -> Int
    {
        return list.keys.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        let key = list.keys![section]
        return list.content[key]!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! TradingRecordCell
        
        let key = list.keys![indexPath.section]
        let record = list.content[key]![indexPath.row]
        
        if record.recordName.contains("付款") {
            cell.amountLabel.text = "-".appending(record.perAmount)
            cell.amountLabel.textColor = UIColor(hex:0x00B050)
        } else {
            cell.amountLabel.text = "+".appending(record.perAmount)
            cell.amountLabel.textColor = UIColor.appOrange
        }
        cell.titleLabel.text = record.recordName
        
        cell.timeLabel.text = (record.dealTime as NSDate).toStringWithNoYear!
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderID") as! TradingRecordHeaderView
        let key = list.keys![section]
        headerView.textLabel!.text = key
        return headerView
    }
    
    // MARK: - UISearchBarDelegate
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        if !tableView.mj_header.isRefreshing() {
            searchBar.resignFirstResponder()
            navigationController!.showLoading()
            refreshHeader()
        }
    }
    
    // MARK: - APIManagerParamSource
    
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        var params: [String: AnyHashable] = [kApiParamPageNo: list.pageNo]
        // 搜索内容
        if let search = searchBar.text {
            params[kApiParamToUserName] = search
        }
        
        if startDate != nil && endDate != nil {
            params[kApiParamStartDate] = (startDate! as NSDate).toDateString
            params[kApiParamEndDate] = (endDate! as NSDate).toDateString
        }
        
        return params
    }
    
    // MARK: - APIManagerCallBackDelegate
    
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!)
    {
        _ = manager.fetchData(with: TransferRecordReformer(recordList: list))
        let toTop: Bool
        if list.pageNo == 0 {
            tableView.mj_header.endRefreshing()
            navigationController?.hideLoading()
            
            outInLabel.text = String(format: "支出 RH %@ 收入 RH %@", list.amountOut, list.amountIn)
            
            if tableView.mj_footer == nil {
                tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(refreshFooter))
            } else {
                tableView.mj_footer.resetNoMoreData()
            }
            toTop = true
            
        } else {
            tableView.mj_footer.endRefreshing()
            toTop = false
        }
        
        if list.isAll {
            tableView.mj_footer.endRefreshingWithNoMoreData()
        }
        tableView.reloadData()
        _recordApiManager = nil
        if toTop {
            _ = tableView.scrollsToTop
        }
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!)
    {
        if list.pageNo == 0 {
            tableView.mj_header.endRefreshing()
            navigationController?.hideLoading()
        } else {
            tableView.mj_footer.endRefreshing()
        }
        alert(manager.errorMessage)
        _recordApiManager = nil
    }
    
    // MARK: - Evnet respond
    /// 下来刷新
    func refreshHeader() {
        list.pageNo = 0
        recordApiManager.loadData()
    }
    
    /// 上拉加载
    func refreshFooter() {
        list.pageNo = list.pageNo+1
        recordApiManager.loadData()
    }
    
    func 点击时间筛选() {
        let vc = DateSelectVC(startDate: startDate, endDate: endDate)
        vc.tapSearch = {[weak self](startDate, endDate) in
            self?.startDate = startDate
            self?.endDate = endDate
            self?.refreshHeader()
        }
        present(vc, animated: true, completion: nil)
    }
    
    // MARK: - Get / Set
    private var startDate: Date?
    private var endDate: Date?
    
    lazy var list = TransferRecordList()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.rowHeight = 83
        tableView.sectionHeaderHeight = 47
        tableView.separatorInset = UIEdgeInsetsMake(0, 19, 0, 0);
        let header = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 62))
        header.addSubview(self.searchBar)
        header.addSubview(self.outInLabel)
        tableView.tableHeaderView = header
        tableView.tableFooterView = UIView()
        tableView.allowsSelection = false
        tableView.backgroundColor = UIColor.appBackground
        return tableView
    }()
    
    
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
        searchBar.searchBarStyle = .minimal
                searchBar.autoresizingMask = .flexibleWidth
        searchBar.placeholder = LocalStr("用户名搜索")
        searchBar.enablesReturnKeyAutomatically = false
        return searchBar
    }()
    
    
    lazy var outInLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 20, y: 44, width: 300, height: 18))
        label.textColor = UIColor.appSubText
        label.font = UIFont.appLightFont(ofPX: 13)
        return label
    }()
    
    private var _recordApiManager: TransferRecordApiManager?
    private var recordApiManager: TransferRecordApiManager {
        if _recordApiManager == nil {
            _recordApiManager = TransferRecordApiManager()
            _recordApiManager!.delegate = self
            _recordApiManager!.paramSource = self
        }
        return _recordApiManager!
    }
    
}
